<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesProdOrderPlanTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
      size="70%"
    >
      <template v-slot:saleCode>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <el-input
          v-model="formDataDialog.saleCode"
          readonly
          :placeholder="$i18n.t('mesProdOrderPlan.msg11')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="mesSalesOrderDialogVisible = true"
          ></el-button>
        </el-input>
      </template>
      <template v-slot:prodCode>
        <el-input
          v-model="formDataDialog.prodCode"
          readonly
          :placeholder="$t('mesPmJtmanager.selectMaterial')"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="baseGoodsDialogVisible2 = true"
          ></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    <ele-dialog-table
      :title="$i18n.t('mesProdOrderPlan.salesOrderQuery')"
      width="1000px"
      :visible.sync="mesSalesOrderDialogVisible"
      :formConfig="mesSalesOrderSearchDialog"
      :column="mesSalesOrderDialogColumn3"
      @getSelectData="getSelectMesSalesOrder1"
      :getList="getSalesOrderList"
      :hasFooter="hasMesSalesOrderFooter"
    >
    </ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesSalesOrder.materialQuery')"
      width="800px"
      :visible.sync="baseGoodsDialogVisible2"
      :formConfig="baseGoodsSearchDialog2"
      :column="baseGoodsDialogColumn2"
      @getSelectData="getSelectBaseGoods2"
      :getList="getBaseGoodsList"
      :hasFooter="hasBaseGoodsFooter"
      :otherParam="{
        // codeList: this.prodCodesList.join(','),
        goodsTypeKey: 'CP,BCP',
      }"
    >
    </ele-dialog-table>
    <ele-dialog-table
      :title="$t('mesProdOrderPlan.modelingQuery')"
      width="1000px"
      :visible.sync="mesTechnologyDialogVisible"
      :column="mesTechnologyDialogColumn"
      @getSelectData="getSelectMesTechnology"
      :getList="getMesTechnologyList"
      :hasFooter="hasMesTechnologyFooter"
      :pagination="false"
      :transFormdata="transFormdatas"
      :initForm="initForm"
    >
    </ele-dialog-table>

    <!-- 导入弹框 -->
    <ele-form-drawer
      size="30%"
      :isLoading="isLoadingImport"
      v-model="importData"
      v-bind="importFormDescDialog"
      :request-fn="handleSubmitImport"
      :visible.sync="importVisible"
      :destroyOnClose="true"
      :title="$i18n.t('mesProdOrderPlan.importUsers')"
    >
      <template v-slot:file="{ desc, data, field, formData }">
        <!-- 插槽内容有el-form-item组件包裹 -->
        <uploadNoAuto @onchange="upLoadHandleChange" ref="uploadNoAuto" />
      </template>
    </ele-form-drawer>
    <!-- <See ref="details" /> -->
    <!-- 排期弹窗 -->
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="pcDescDialog"
      v-bind="pcformDescDialog"
      :request-fn="pqHandleSubmit"
      :visible.sync="visibleAddOrder"
      :title="title"
      size="90%"
    >
      <template v-slot:orderList="{ desc }">
        <div>
          <el-button
            @click.native.prevent="addBtn"
            type="primary"
            size="small"
            >{{ $t("common.add") }}</el-button
          >
          <el-form ref="pcDescDialog" :model="pcDescDialog" :rules="rules">
            <el-table
              :data="pcDescDialog.orderList.filter((ite) => ite.addFlag != 3)"
              style="width: 100%; margin-top: 10px"
              height="calc(100vh - 350px)"
              :header-cell-class-name="starAdd"
            >
              <el-table-column
                :label="$i18n.t('common.order')"
                type="index"
                width="50"
                fixed="left"
                align="center"
              >
              </el-table-column>
              <el-table-column
                fixed="left"
                align="center"
                :label="$t('mesProdOrderPlan.codeStrategy')"
                width="220"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-input
                      v-if="!!pcDescDialog.codeStrategy && !scope.row.orderCode"
                      :disabled="true"
                      v-model="codeStrategy"
                    >
                    </el-input>
                    <!-- {{ scope.row.orderCode }} -->

                    <el-input
                      :disabled="!!pcDescDialog.codeStrategy || !!scope.row.id"
                      v-model="scope.row.orderCode"
                      :placeholder="$t('common.input')"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                :label="$t('mesProdOrderPlan.bomVersionNumber')"
                width="140"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select
                      v-model="scope.row.bomVersionNumber"
                      :disabled="true"
                      :placeholder="$t('common.select')"
                      filterable
                    >
                      <el-option
                        v-for="item in bomVersionNumberList"
                        :key="item.id"
                        :label="item.bomVersion"
                        :value="item.bomVersion"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                :label="$t('mesProdOrderPlan.workshopName')"
                width="140"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select
                      v-model="scope.row.workshopCode"
                      @change="
                        (val) => {
                          workshopSelect(val, scope.$index);
                        }
                      "
                      :placeholder="$t('common.select')"
                      :disabled="!scope.row.operFlag"
                      filterable
                    >
                      <el-option
                        v-for="item in workshopList"
                        :key="item.modelingCode"
                        :label="item.modelingName"
                        :value="item.modelingCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                :label="$t('mesCoEsopInfo.line')"
                width="140"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select
                      v-model="scope.row.lineCode"
                      @change="
                        (val) => {
                          lineSelect(val, scope.$index);
                        }
                      "
                      :placeholder="$t('common.select')"
                      filterable
                      :disabled="scope.row.lineDisabled || !scope.row.operFlag"
                    >
                      <el-option
                        v-for="item in scope.row.lineList"
                        :key="item.modelingCode"
                        :label="item.modelingName"
                        :value="item.modelingCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('mesCoEsopInfo.csiProcessFileNameEntity')"
                width="200"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-input
                      v-model="scope.row.technologyName"
                      readonly
                      :placeholder="$t('mesProdOrderPlan.selectProcess')"
                      :disabled="!scope.row.operFlag"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="selectTechnology(scope.$index)"
                        :disabled="!scope.row.operFlag"
                      ></el-button>
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('mesProdOrderPlan.versionNumber')"
                width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-input
                      v-model="scope.row.versionNumber"
                      :disabled="true"
                    >
                    </el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column
                :label="$t('mesCoEsopInfo.station')"
                width="140"
                v-if="false"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select
                      v-model="scope.row.stationCode"
                      @change="
                        (val) => {
                          stationSelect(val, scope.$index);
                        }
                      "
                      :placeholder="$t('common.select')"
                      filterable
                    >
                      <el-option
                        v-for="item in scope.row.stationList"
                        :key="item.modelingCode"
                        :label="item.modelingName"
                        :value="item.modelingCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column> -->
              <!-- <el-table-column
                :label="$t('mesProdOrderPlan.equipment')"
                width="140"
                v-if="false"
              >
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select
                      v-model="scope.row.equipmentCode"
                      :placeholder="$t('common.select')"
                      @change="
                        (val) => {
                          equipmentSelect(val, scope.$index);
                        }
                      "
                      filterable
                    >
                      <el-option
                        v-for="(item, index) in scope.row.equipmentList"
                        :key="item.equipmentCode + index"
                        :label="item.equipmentName"
                        :value="item.equipmentCode"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column> -->
              <el-table-column
                :label="$t('mesProdOrderPlan.planBeginDate')"
                width="130"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'orderList.' + scope.$index + '.planBeginDate'"
                    :rules="rules.planBeginDate"
                  >
                    <el-date-picker
                      v-model="scope.row.planBeginDate"
                      type="date"
                      :disabled="!scope.row.operFlag"
                      :clearable="false"
                      @change="(val) => startDateChange(val, scope.$index)"
                      value-format="yyyy-MM-dd"
                      :placeholder="$t('ele-form.date')"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('mesProdOrderPlan.planEndDate')"
                width="130"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'orderList.' + scope.$index + '.planEndDate'"
                    :rules="rules.planEndDate"
                  >
                    <el-date-picker
                      v-model="scope.row.planEndDate"
                      @change="(val) => endDateChange(val, scope.$index)"
                      type="date"
                      :clearable="false"
                      :disabled="!scope.row.operFlag"
                      value-format="yyyy-MM-dd"
                      :placeholder="$t('ele-form.date')"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--订单状态 -->
              <el-table-column
                :label="$t('mesProdOrderPlan.orderStatus')"
                width="120"
                fixed="right"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'orderList.' + scope.$index + '.orderStatus'"
                    :rules="rules.quantity"
                  >
                    <el-select
                      v-model="scope.row.orderStatus"
                      :placeholder="$t('common.select')"
                      :disabled="true"
                    >
                      <el-option
                        v-for="item in statusList"
                        :key="item.value"
                        :label="item.description"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('mesSalesOrder.count')"
                width="150"
                fixed="right"
                align="center"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'orderList.' + scope.$index + '.quantity'"
                    :rules="rules.quantity"
                  >
                    <el-input-number
                      v-model="scope.row.quantity"
                      readonly
                      :min="0.1"
                      :precision="1"
                      :step="0.1"
                      :disabled="!scope.row.operFlag"
                    >
                    </el-input-number>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                :label="$t('common.operation')"
                width="100"
              >
                <template slot-scope="scope">
                  <el-button
                    @click.native.prevent="
                      copyRow(scope.$index, pcDescDialog.orderList)
                    "
                    type="text"
                    size="small"
                  >
                    {{ $t("common.copy") }}
                  </el-button>
                  <el-button
                    @click.native.prevent="
                      deleteRow(scope.$index, pcDescDialog.orderList)
                    "
                    type="text"
                    size="small"
                    style="color: red"
                    v-if="scope.row.operFlag"
                  >
                    {{ $t("common.delete") }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </template>
    </ele-form-drawer>
  </div>
</template>

<script>
import See from "./see.vue";
import {
  operateList,
  searchConfig,
  importFormDescDialog,
  formDescDialogMixin,
  rowConfig,
  sendThis,
} from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  importData,
  getOrderStatusList,
  salesDetail,
  getSalesOrderList, //获取销售订单
  getProdOrderTypeList,
  subBatchOrder,
  getMesProdOrderListByPlanCode,
  batchGenerateOrder,
} from "@/api/order/mesProdOrderPlan";
import {
  getLineCodeList, //查询线体
  getLineCodeListNew,
  getStationCodeList,
  getequipmentCodeList,
  getModelSetting,
  getBomVersionList,
} from "@/api/order/mesProdOrder";
import { getUnitDictList } from "@/api/common";
import { mesSalesOrderDialog } from "./mixin";
import { baseGoodsDialog2 } from "./mixinGoods";
import { pqformDescDialog } from "./scheduling";
import { mesTechnologyDialog } from "./mixinTechnology";
import { getBaseCodeStrategy, getDict } from "@/api/common";
import url from "@/axios/url";
const { minioUrl } = url();
import { popover } from "@/utils/judge";

export default {
  name: "mesProdOrderPlan",
  mixins: [
    mesSalesOrderDialog,
    baseGoodsDialog2,
    formDescDialogMixin,
    pqformDescDialog,
    mesTechnologyDialog,
    searchConfig,
  ],
  data() {
    const _this = this;
    return {
      title: null,
      statusList: [],
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      // formDescDialog, //新增修改框
      // searchConfig,
      operateList,
      getList,
      dictList: [],
      isLoadingImport: false, // 导入数据loading
      prodCodesList: [],
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      editWorkshopList: [],
      editLineList: [],
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          width: 60,
          fixed: "left",
        },

        {
          prop: "planCode",
          label: $i18n.t("mesProdOrderPlan.productionOrderCode"),
          width: 200,
          showOverflowTooltip: true,
          fixed: "left",
          render: (h, { row }) => {
            return popover(row.planCode, h, "", () => this.goDetails(row));
            // return (
            //   <el-link
            //     on={{
            //       click: () => _this.goDetails(row),
            //     }}
            //     type="primary"
            //   >
            //     {row.planCode}
            //   </el-link>
            // );
          },
        },

        //    {
        //        prop: "saleCode",
        //                label: "销售订单编码",
        //            width: 200,
        //            showOverflowTooltip: true,
        //            render: (h, { row }) => {
        //        return (
        //                <el-link
        //        on={{
        //                click: () => _this.goworkDetails(row),
        //                }}
        //        type="primary"
        //                >
        //                {row.saleCode}
        //                </el-link>
        //            );
        //    },
        //    },

        {
          prop: "prodCode",
          label: $i18n.t("mesProdOrderPlan.prodCode"),
          width: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesProdOrderPlan.prodName"),
          width: 200,
          showOverflowTooltip: true,
        },
        {
          prop: "orderStatus",
          label: $i18n.t("mesProdOrderPlan.orderStatus"),
          minWidth: 100,
          showOverflowTooltip: true,
          fixed: "right",
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getOrderStatusList();
            return list.data.result || [];
          },
        },
        {
          prop: "workshopName",
          label: $i18n.t("mesProdOrderPlan.workshopName"),
          minWidth: 180,
        },
        {
          prop: "lineName",
          label: $i18n.t("mesProdOrderPlan.lineName"),
          minWidth: 180,
        },

        {
          prop: "quantity",
          label: $i18n.t("mesProdOrderPlan.planQuantity"),
          minWidth: 120,
        },
        {
          prop: "qualifiedQty",
          label: $i18n.t("mesProdOrderPlan.qualifiedQty"),
          minWidth: 140,
        },
        {
          prop: "unqualifiedQty",
          label: $i18n.t("mesProdOrderPlan.unqualifiedQty"),
          minWidth: 160,
        },
        {
          prop: "planBeginDate",
          label: $i18n.t("mesProdOrderPlan.planBeginDate"),
          width: 130,
        },
        {
          prop: "planEndDate",
          label: $i18n.t("mesProdOrderPlan.planEndDate"),
          width: 130,
        },
        {
          prop: "actualBeginDate",
          label: $i18n.t("mesProdOrderPlan.actualBeginDate"),
          width: 130,
        },
        {
          prop: "actualEndDate",
          label: $i18n.t("mesProdOrderPlan.actualEndDate"),
          width: 130,
        },
        {
          prop: "bomVersionNumber",
          label: $i18n.t("mesProdOrderPlan.bomVersionNumber"),
          minWidth: 180,
        },
        {
          prop: "unit",
          label: $i18n.t("mesProdOrderPlan.measureUnit"),
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: "unitCode",
          label: $i18n.t("mesProdOrderPlan.measureUnitCode"),
          minWidth: 140,
          showOverflowTooltip: true,
        },
        {
          prop: "prodOrderType",
          label: $i18n.t("mesProdOrderPlan.prodOrderType"),
          minWidth: 170,
          showOverflowTooltip: true,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getProdOrderTypeList();
            return list.data.result;
          },
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 180,
        },

        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 180,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 160,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
      visibleAddOrder: false,
      pcDescDialog: {
        orderList: [],
      },
      lineList: [], // 线体
      workshopList: [], //车间
      stationList: [], // 工位
      equipmentList: [], // 设备
      bomVersionNumberList: [],
      initForm: {},
      techIndex: null,
      rules: {
        planEndDate: [
          {
            required: true,
            message: $i18n.t("mesProdOrderPlan.startDateRequired"),
            trigger: "change",
          },
        ],
        planBeginDate: [
          {
            required: true,
            message: $i18n.t("mesProdOrderPlan.endDateRequired"),
            trigger: "change",
          },
        ],
        quantity: [
          {
            required: true,
            message: $i18n.t("mesProdOrderPlan.quantityRequired"),
            trigger: "change",
          },
        ],
      },
      codeStrategy: $i18n.t("mesProdOrderPlan.autoGenerate"),
      codeStrategystr: $i18n.t("mesProdOrderPlan.autoGenerate"),
      getDictList: [], // 计量单位字典列表
    };
  },
  components: { See },
  computed: {},
  mounted() {
    sendThis(this);
    this.orderStatusList();
  },
  methods: {
    starAdd(obj, rowIndex) {
      if (obj.columnIndex === 10) {
        return "star";
      }
    },
    //开始日期判断
    handleStartDate(val) {
      const { planEndDate } = this.formDataDialog;
      if (val && planEndDate) {
        if (new Date(val).getTime() > new Date(planEndDate).getTime()) {
          this.$message.error($i18n.t("mesProdOrderPlan.startDateLimit"));
          this.$set(this.formDataDialog, "planBeginDate", null);
        }
      }
    },
    handleEndDate(val) {
      const { planBeginDate, planDeliveryDate } = this.formDataDialog;
      if (val && planBeginDate) {
        if (new Date(planBeginDate).getTime() > new Date(val).getTime()) {
          this.$message.error($i18n.t("mesProdOrderPlan.endDateLimit"));
          this.$set(this.formDataDialog, "planEndDate", null);
          return;
        }
      }
      // if (planDeliveryDate && val) {
      //   if (new Date(val).getTime() > new Date(planDeliveryDate).getTime()) {
      //     this.$message.error(
      //       `计划结束日期应小于或等于交付日期${planDeliveryDate}`
      //     );
      //     this.$set(this.formDataDialog, "planEndDate", null);
      //   }
      // }
    },
    // 排期日期判断
    startDateChange(val, i) {
      const { planEndDate } = this.pcDescDialog;
      const planEndDate2 = this.pcDescDialog.orderList[i].planEndDate;
      // if (planEndDate && val) {
      //   if (new Date(val).getTime() > new Date(planEndDate).getTime()) {
      //     this.$message.error(`开始日期应小于或等于结束日期${planEndDate}`);
      //     this.$set(this.pcDescDialog.orderList[i], "planBeginDate", null);
      //   }
      // }
      if (val && planEndDate2) {
        if (new Date(val).getTime() > new Date(planEndDate2).getTime()) {
          this.$message.error($i18n.t("mesProdOrderPlan.startDateLimit"));
          this.$set(this.pcDescDialog.orderList[i], "planBeginDate", null);
        }
      }
    },
    endDateChange(val, i) {
      const { planEndDate } = this.pcDescDialog;
      const planBeginDate = this.pcDescDialog.orderList[i].planBeginDate;
      if (val && planBeginDate) {
        if (new Date(planBeginDate).getTime() > new Date(val).getTime()) {
          this.$message.error($i18n.t("mesProdOrderPlan.endDateLimit"));
          this.$set(this.pcDescDialog.orderList[i], "planEndDate", null);
          return;
        }
      }
      // if (planEndDate && val) {
      //   if (new Date(val).getTime() > new Date(planEndDate).getTime()) {
      //     this.$message.error(`结束日期应小于或等于交付日期${planEndDate}`);
      //     this.$set(this.pcDescDialog.orderList[i], "planEndDate", null);
      //   }
      // }
    },
    //跳转详情页
    goDetails(row) {
      this.$router.push({
        path: "/order/mesProdOrderPlan/see",
        query: { id: row.planCode },
      });
    },
    //跳转销售详情页
    goworkDetails(row) {
      //saleCode
      this.$router.push({
        path: "/order/mesSalesOrder/detail",
        query: { id: row.saleCode },
      });
      // this.$refs.details.init(row);
    },
    getSalesDetail(salesOrderCode) {
      this.formDataDialog.prodCode = "";
      salesDetail({ salesOrderCode }).then((res) => {
        const result = res.data.result || [];
        const prodCodesList = result.map((val) => val.prodCode);
        this.prodCodesList = [...new Set(prodCodesList)];
        console.log("xiao", this.prodCodesList);
      });
    },
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {
            orderStatus: "-1",
          };
          this.visible = true;
          this.prodCodesList = [];
          this.addChekCodeStrategy();
        },
        deleteBatch: () => {
          this.$confirm(
            $i18n.t("common.deleteBatch", {
              name: $i18n.t("mesProdOrderPlan.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },

        exportExcel: () => {
          // window.open(
          //   "http://9000.gr817115.m6tfe15g.ceb51d.grapps.cn/file-template/生产订单模板.xls"
          // );
          var url = `${minioUrl}/mes-template/生产订单模板.xls`;
          // console.log("aaaaaaa=", url);
          window.open(url);
        },
        import: () => {
          this.importDialogData = {};
          this.importVisible = true;
        },
        addOrder: () => {
          this.pqrowDetail(data.rows[0].id, data.rows[0].planCode);
          this.initDailogTableOptions(data.rows[0].prodCode);
        },
      };
      fnc[data.handleName]();
    },
    async initDailogTableOptions(prodCode) {
      try {
        const list = await getLineCodeListNew({
          modelingCode: this.$store.getters.factoryCode,
          level: 4,
          modelingType: "0",
        });
        this.workshopList = list.data.result || [];
        const bomList = await getBomVersionList({
          materialCode: prodCode,
          bomStatus: 1,
        });
        this.bomVersionNumberList = bomList.data.result || [];
      } finally {
        this.getBaseCodeStrategy();
      }
    },
    async stationSelect(val, i) {
      this.stationList.forEach((v) => {
        if (val == v.modelingCode)
          this.$set(
            this.pcDescDialog.orderList[i],
            "stationName",
            v.modelingName
          );
      });
      this.pcDescDialog.orderList[i].equipmentName = "";
      this.pcDescDialog.orderList[i].equipmentCode = "";
      const params = {
        modelingCode: val,
      };
      const list = await getequipmentCodeList(params);
      this.$set(
        this.pcDescDialog.orderList[i],
        "equipmentList",
        list.data.result || []
      );
    },
    async workshopSelect(val, i, bool) {
      console.log("输出选择的车间123：", val, i);
      const workshopCode = val;
      // 是否需要赋值name，刚进页面接口返回了name，不需要再次循环
      if (!bool) {
        this.workshopList.forEach((v) => {
          if (val == v.modelingCode)
            this.$set(
              this.pcDescDialog.orderList[i],
              "workshopName",
              v.modelingName
            );
        });
        this.$set(this.pcDescDialog.orderList[i], "workshopCode", workshopCode);
        this.$set(this.pcDescDialog.orderList[i], "lineCode", "");
        this.$set(this.pcDescDialog.orderList[i], "lineName", "");
        this.$set(this.pcDescDialog.orderList[i], "stationCode", "");
        this.$set(this.pcDescDialog.orderList[i], "stationName", "");
        this.$set(this.pcDescDialog.orderList[i], "equipmentName", "");
        this.$set(this.pcDescDialog.orderList[i], "equipmentCode", "");
        this.$set(this.pcDescDialog.orderList[i], "stationList", []);
        this.$set(this.pcDescDialog.orderList[i], "equipmentList", []);
      }
      const params = {
        level: 5,
        modelingCode: val,
      };
      const list = await getLineCodeList(params);
      this.$set(
        this.pcDescDialog.orderList[i],
        "lineList",
        list.data.result || []
      );
      // 根据车间编码获取报工信息
      let res = await getModelSetting({ workshopCode: val });
      if (res.data.success) {
        let { reportType, reportWay } = res.data.result.records[0] ?? [
          { reportType: "", reportWay: "" },
        ];

        // 根据报工类型和报工方式调整线体、工艺流程、工位、设备的禁用方式
        let lineDisabled = this.changeByLineDisabledReportType(
          reportType,
          reportWay
        );
        this.$set(this.pcDescDialog.orderList[i], "lineDisabled", lineDisabled); // 是否禁用线体
        let techDisabled = this.changeByTechDisabledReportType(
          reportType,
          reportWay
        );
        this.$set(this.pcDescDialog.orderList[i], "techDisabled", techDisabled); // 是否禁用工序
        if (lineDisabled) {
          this.$set(this.pcDescDialog.orderList[i], "lineCode", "");
          this.$set(this.pcDescDialog.orderList[i], "lineName", "");
        }
        if (techDisabled) {
          this.$set(this.pcDescDialog.orderList[i], "technologyCode", "");
          this.$set(this.pcDescDialog.orderList[i], "technologyName", "");
        }

        this.$set(this.pcDescDialog.orderList[i], "reportType", ""); // 报工类型
        this.$set(this.pcDescDialog.orderList[i], "reportWay", ""); // 报工方式
      }
      // else {
      //   this.$message.success("该车间未关联智造模型");
      // }
    },
    changeByLineDisabledReportType(reportType, reportWay) {
      // 工单报工-统一报工 显示车间（必选）、设备（非必选）
      if (
        reportType == "mes_report_type_order" &&
        reportWay == "report_way_unite"
      ) {
        return true;
      } else if (
        reportType == "mes_report_type_order" &&
        reportWay == "report_way_process"
      ) {
        // 工单报工-按工序报工 显示车间（必选）、工艺流程（必选）、设备（非必选）
        return true;
      } else if (reportType == "mes_report_type_process") {
        // 工序报工 显示车间（必选）、线体（非必填）、工艺流程（必选）、工位（非必选）、设备（非必选）
        return false;
      } else if (reportType == "mes_report_type_workcell") {
        // 工位报工 显示车间（必选）、线体（非必填）、工艺流程（必选）、工位（非必选）、设备（非必选）
        return false;
      } else {
        return true;
      }
    },
    changeByTechDisabledReportType(reportType, reportWay) {
      return false; //改为所有报工模式，工艺流程都可自行选择
      // // 工单报工-统一报工 显示车间（必选）、设备（非必选）
      // if (
      //   reportType == "mes_report_type_order" &&
      //   reportWay == "report_way_unite"
      // ) {
      //   return false;
      // } else if (
      //   reportType == "mes_report_type_order" &&
      //   reportWay == "report_way_process"
      // ) {
      //   // 工单报工-按工序报工 显示车间（必选）、工艺流程（必选）、设备（非必选）
      //   return false;
      // } else if (reportType == "mes_report_type_process") {
      //   // 工序报工 显示车间（必选）、线体（非必填）、工艺流程（必选）、工位（非必选）、设备（非必选）
      //   return false;
      // } else if (reportType == "mes_report_type_workcell") {
      //   // 工位报工 显示车间（必选）、线体（非必填）、工艺流程（必选）、工位（非必选）、设备（非必选）
      //   return false;
      // } else {
      //   return true;
      // }
    },
    async lineSelect(val, i) {
      this.pcDescDialog.orderList[i].lineList.forEach((v) => {
        if (val == v.modelingCode)
          this.$set(this.pcDescDialog.orderList[i], "lineName", v.modelingName);
      });
      this.$set(this.pcDescDialog.orderList[i], "stationCode", "");
      this.$set(this.pcDescDialog.orderList[i], "stationName", "");
      this.pcDescDialog.orderList[i].equipmentName = "";
      this.pcDescDialog.orderList[i].equipmentCode = "";
      this.$set(this.pcDescDialog.orderList[i], "equipmentList", []);
      if (!this.pcDescDialog.orderList[i].technologyId) return;
      const params = {
        lineCode: val,
        technologyId: this.pcDescDialog.orderList[i].technologyId,
      };
      const list = await getStationCodeList(params);
      this.$set(
        this.pcDescDialog.orderList[i],
        "stationList",
        list.data.result || []
      );
    },

    async equipmentSelect(val, i) {
      this.equipmentList.forEach((v) => {
        if (val == v.equipmentCode)
          this.$set(
            this.pcDescDialog.orderList[i],
            "equipmentName",
            v.equipmentName
          );
      });
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
          this.addChekCodeStrategy();
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
          this.addChekCodeStrategy();
        },
        delete: () => {
          this.$confirm(
            $i18n.t("common.deleteSingle", {
              name: $i18n.t("mesProdOrderPlan.name"),
            }),
            $i18n.t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.id);
          });
        },
      };
      fnc[handleName]();
    },
    selectTechnology(index) {
      this.initForm = {
        prodCode: this.pcDescDialog.prodCode,
        seriesCode: this.pcDescDialog.seriesCode,
        workshopCode: this.pcDescDialog.orderList[index].workshopCode,
      };
      this.mesTechnologyDialogVisible = true;
      this.techIndex = index;
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      // let { modelingName } = this.workshopList.find(
      //   (ite) => ite.modelingCode == data.workshopCode
      // ) || {
      //   modelingName: "",
      // };
      // data.workshopName = modelingName;

      // getDictList
      // let { value, description } = this.getDictList.find((ite) => ite.value == data.measureUnits) || {
      //   measureUnits: ''
      // }
      // data.measureUnits = description
      // data.measureUnitsCode = value

      // console.log("新增生产订单提交数据111122：",data)

      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      delete data.userDefined1; // 删除不需要修改的非主键字段
      delete data.userDefined2; // 删除不需要修改的非主键字段
      delete data.userDefined3; // 删除不需要修改的非主键字段
      delete data.userDefined4; // 删除不需要修改的非主键字段
      delete data.userDefined5; // 删除不需要修改的非主键字段
      delete data.userDefined6; // 删除不需要修改的非主键字段
      delete data.userDefined7; // 删除不需要修改的非主键字段
      delete data.userDefined8; // 删除不需要修改的非主键字段
      delete data.userDefined9; // 删除不需要修改的非主键字段
      delete data.userDefined10; // 删除不需要修改的非主键字段
      delete data.createBy; // 删除不需要修改的非主键字段
      delete data.createByName; // 删除不需要修改的非主键字段
      delete data.createTime; // 删除不需要修改的非主键字段
      delete data.updateBy; // 删除不需要修改的非主键字段
      delete data.updateByName; // 删除不需要修改的非主键字段
      delete data.updateTime; // 删除不需要修改的非主键字段
      delete data.activeFlag; // 删除不需要修改的非主键字段
      const params = this.formDataDialog.id
        ? { title: $i18n.t("common.editSuccess"), api: rowUpdate, data }
        : { title: $i18n.t("common.addSuccess"), api: rowCreate, data };
      this.doSubmit(params);
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
        salesDetail({ salesOrderCode: this.formDataDialog.saleCode }).then(
          (res) => {
            const result = res.data.result || [];
            const prodCodesList = result.map((val) => val.prodCode);
            this.prodCodesList = [...new Set(prodCodesList)];
            console.log("xiao", this.prodCodesList);
          }
        );
      });
    },
    pqrowDetail(id, planCode) {
      this.pcDescDialog = {};
      rowDetail(id).then(async (res) => {
        // let {
        //   workshopCode,
        //   workshopName,
        //   lineCode,
        //   lineName,
        //   bomVersionNumber,
        //   orderStatus,
        // } = res.data.result;
        this.pcDescDialog = {
          ...res.data.result,
          orderList: [
            // {
            //   equipmentCode: '',
            //   lineList: [], // 线体
            //   stationList: [], // 工位
            //   equipmentList: [], // 设备
            //   bomVersionNumberList: [],
            //   workshopCode,
            //   workshopName,
            //   lineCode,
            //   lineName,orderStatus
            // }
          ],
        };
        // 获取排期列表
        let res1 = await getMesProdOrderListByPlanCode({ planCode });

        this.pcDescDialog.orderList = (res1.data.result || []).map((ite, i) => {
          let {
            workshopCode,
            workshopName,
            lineCode,
            lineName,
            bomVersionNumber,
            orderStatus,
            id,
            orderCode,
            technologyId,
            technologyCode,
            technologyName,
            versionNumber,
            stationCode,
            stationName,
            equipmentCode,
            equipmentName,
            planBeginDate,
            planEndDate,
            quantity,
            operFlag,
          } = ite;
          this.workshopSelect(workshopCode, i, true);
          // this.lineSelect(lineCode, i);
          return {
            id,
            equipmentCode: "",
            lineList: [], // 线体
            stationList: [], // 工位
            equipmentList: [], // 设备
            bomVersionNumberList: [],
            orderCode,
            technologyId,
            technologyCode,
            technologyName,
            versionNumber,
            stationCode,
            stationName,
            equipmentCode,
            equipmentName,
            planBeginDate,
            planEndDate,
            quantity,
            workshopCode,
            workshopName,
            lineCode,
            lineName,
            bomVersionNumber,
            orderStatus,
            operFlag,
            addFlag: operFlag ? 2 : 4,
          };
        });
        //   await this.workshopSelect(workshopCode, 0);
        // this.$set(this.pcDescDialog.orderList[0], "lineCode", lineCode);
        // this.$set(this.pcDescDialog.orderList[0], "lineName", lineName);
        // if (bomVersionNumber) {
        //   this.$set(
        //     this.pcDescDialog.orderList[0],
        //     "bomVersionNumber",
        //     bomVersionNumber
        //   );
        // }
        //   await this.lineSelect(lineCode, 0);
      });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, "file", file);
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t("common.uploadMsg"));
        return;
      }
      const formData = new FormData();
      formData.append("file", this.importData.file.get("file"));
      this.isLoadingImport = true;
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t("common.importSuccess"));
          this.isLoadingImport = false;
          this.importVisible = false;
          this.refresh();
        })
        .catch((error) => {
          console.log("错误", error);
          this.$set(this.importData, "file", null);
        })
        .finally(() => {
          this.isLoadingImport = false;
          this.$refs.uploadNoAuto.clearFiles();
        });
    },
    pqHandleSubmit() {
      this.$refs.pcDescDialog.validate((valid) => {
        if (valid) {
          let data = {
            id: this.pcDescDialog.id,
            orderCodeStrategy: this.pcDescDialog.codeStrategy,
            orderList: this.pcDescDialog.orderList,
          };
          this.isLoading = true;
          batchGenerateOrder(data)
            .then(() => {
              this.$message.success($i18n.t("common.saveSuccess"));
              this.visibleAddOrder = false;
              this.refresh();
            })
            .finally(() => {
              this.isLoading = false;
            });
        } else {
          this.$message.warning($i18n.t("mesProdOrderPlan.pleaseCompleteInfo"));
        }
      });
    },
    deleteRow(index, rows) {
      // 非新增复制的数据
      if (rows[index].id) {
        rows[index].addFlag = 3;
      } else {
        rows.splice(index, 1);
      }
    },
    copyRow(index, rows) {
      // operFlag 可以编辑的控制， orderStatus默认待下发

      let obj = {
        ...rows[index],
        operFlag: true,
        orderStatus: "0",
        addFlag: 1,
        orderName: "",
        orderCode: this.pcDescDialog.codeStrategy
          ? $i18n.t("mesProdOrderPlan.autoGenerate")
          : "",
      };
      delete obj.id;
      rows.push({
        ...obj,
        operFlag: true,
        orderStatus: "0",
        addFlag: 1,
      });
    },

    // 获取工单状态
    async orderStatusList() {
      let res = await getDict("prod_order_status");
      this.statusList = res.data.result || [];
    },
    async addBtn() {
      let { workshopCode, workshopName, lineCode, lineName, bomVersionNumber } =
        this.pcDescDialog;
      this.pcDescDialog.orderList.push({
        orderCode: this.pcDescDialog.codeStrategy
          ? $i18n.t("mesProdOrderPlan.autoGenerate")
          : "",
        planBeginDate: this.pcDescDialog.planBeginDate,
        planEndDate: this.pcDescDialog.planEndDate,
        quantity: this.pcDescDialog.quantity,
        workshopCode,
        workshopName,
        lineCode,
        lineName,
        bomVersionNumber,
        operFlag: true,
        orderStatus: "0",
        addFlag: 1,
      });
      // operFlag 可以编辑的控制， orderStatus默认待下发
      let index = Number(this.pcDescDialog.orderList.length) - 1;

      await this.workshopSelect(workshopCode, index);
      this.$set(this.pcDescDialog.orderList[index], "lineCode", lineCode);
      this.$set(this.pcDescDialog.orderList[index], "lineName", lineName);
      this.$set(
        this.pcDescDialog.orderList[index],
        "bomVersionNumber",
        bomVersionNumber
      );
      console.log(
        1111111111,
        workshopCode,
        workshopName,
        lineCode,
        lineName,
        bomVersionNumber
      );
      if (lineCode) {
        await this.lineSelect(lineCode, 0);
      }
    },
    addChekCodeStrategy() {
      getBaseCodeStrategy({
        code: "planordercode",
        system: "default",
        strategyStatus: "1",
      }).then((res) => {
        // console.log("判断是否存在编码规则", res);
        const result = res.data.result;
        let code =
          Array.isArray(result) && result.length > 0 ? result[0].code : "";
        this.$set(this.formDataDialog, "codeStrategy", code);
        this.$set(
          this.formDescDialog.formDesc.planCode,
          "required",
          code ? false : true
        );
      });
    },
    //判断是否存在编码规则
    getBaseCodeStrategy() {
      getBaseCodeStrategy({
        code: "planordercode",
        system: "default",
        strategyStatus: "1",
      })
        .then((res) => {
          const result = res.data.result;
          this.pcDescDialog.codeStrategy =
            Array.isArray(result) && result.length > 0 ? result[0].code : "";
        })
        .finally(() => {
          this.visibleAddOrder = true;
          // this.this.pcDescDialog.orderList[0].lineList = []
          // this.this.pcDescDialog.orderList[0].stationList = []
          // this.this.pcDescDialog.orderList[0].equipmentList = []
          // console.log(888, this.pcDescDialog.orderList);
          if (this.pcDescDialog.orderList.length == 0) {
            return;
          }

          // this.$set(
          //   this.pcDescDialog.orderList[0],
          //   "orderCode",
          //   this.pcDescDialog.codeStrategy
          // );
          // this.$set(
          //   this.pcDescDialog.orderList[0],
          //   "planBeginDate",
          //   this.pcDescDialog.planBeginDate
          // );
          // this.$set(
          //   this.pcDescDialog.orderList[0],
          //   "planEndDate",
          //   this.pcDescDialog.planEndDate
          // );
          // this.$set(
          //   this.pcDescDialog.orderList[0],
          //   "quantity",
          //   this.pcDescDialog.quantity
          // );
        });
    },
  },
};
</script>
<style scoped lang="scss">
.el-form-item--small.el-form-item {
  margin-bottom: 0;
}

/deep/.el-table th.star div::after {
  content: "*";
  font-size: 15px;
  color: red;
}
</style>
